﻿using AduSkin.Controls.Metro;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// AddHeart.xaml 的交互逻辑
    /// </summary>
    public partial class AddHeart : UserControl
    {
        public AddHeart()
        {
            InitializeComponent();
            //this.HeartIP.Text = App.CurrIP;
            initDataAllCard();
            if (App.isMaster != null)
            {
                if (!App.isMaster.Value)
                {
                    panelSlaveLabel.Visibility = Visibility.Visible;
                    panelSlaveSelect.Visibility = Visibility.Visible;
                    GetMasterIP();
                }

            }
        }

        public void initDataAllCard() {
            var adapterList = NetWorkHelper.GetNetworkInfo();
            foreach (var adapter in adapterList)
            {
                string Name = adapter.Name;
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = Name;
                AdapterSelector.Items.Add(cbi);
            }
        }

        public async void GetMasterIP()
        {
            var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
            //访问主机是否存在
            //请求主机的接口，是否存在数据
            var result = await HttpHelpers.Get<HttpResponseResultModel<List<HeartEntity>>>($"{masterPath}{ConfigurationManager.AppSettings["getMasterHeartInfo"]?.ToString() ?? "getMasterHeartInfo"}");
            if (result.IsSuccess)
            {
                foreach (var item in result.BackResult)
                {
                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Content = item.HeartIP;
                    MasterHeartIPBind.Items.Add(cbi);
                }
            }
        }

        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(NodeName.Text))
            {
                AduMessageBoxs.Show("节点名称不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(HeartName.Text))
            {
                AduMessageBoxs.Show("节点名称不能为空！");
                return;
            }
            if (!NetWorkHelper.ValidateIpAddress(HeartIP.Text))
            {
                AduMessageBoxs.Show("请填写正确的心跳IP！");
                return;
            }
            else
            {
                if (!NetWorkHelper.ValidateIPIsCurrIP(HeartIP.Text))
                {
                    AduMessageBoxs.Show("该心跳IP不是本地合法的IP，请检查！");
                    return;
                }
            }

           

            if (App.isMaster != null)
            {
                if (!App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(MasterHeartIPBind.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
                    {
                        AduMessageBoxs.Show("请绑定主机IP");
                        return;
                    }

                    if (!NetWorkHelper.ValidateIPIsWithNetworkSegment(HeartIP.Text, MasterHeartIPBind.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
                    {
                        AduMessageBoxs.Show("请选择同网段IP！");
                        return;
                    }
                }
            }



            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定设置{HeartIP.Text}为心跳IP吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {
                var isSuccess = 0;
                SQLiteHelper.ExecuteSql("delete from HeartManage");
                if (App.isMaster.Value)
                {
                    isSuccess = SQLiteHelper.ExecuteSql($"insert into HeartManage (NodeName,HeartName,HeartIP,IsLocal,CreateTime)" +
                   $" values('{NodeName.Text}','{HeartName.Text}','{HeartIP.Text}','true','{DateTime.Now.ToString()}')");
                     
                    App.XtIP = HeartIP.Text;
                }
                else
                {
                    isSuccess = SQLiteHelper.ExecuteSql($"insert into HeartManage (NodeName,HeartName,HeartIP,IsLocal,MasterHeartIPBind,CreateTime)" +
                         $" values('{NodeName.Text}','{HeartName.Text}','{HeartIP.Text}','true','{MasterHeartIPBind.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")}','{DateTime.Now.ToString()}')");
                    App.XtIP = MasterHeartIPBind.SelectedValue.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "");
                    #region 上传心跳给主机
                    var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                    var parms = new HeartEntity
                    {
                        HeartIP = HeartIP.Text,
                    };
                    await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                         (ConfigurationManager.AppSettings["setBindHeartInfo"]?.ToString() ?? "setBindHeartInfo"), JsonConvert.SerializeObject(parms));
                    #endregion
                }

                if (isSuccess <= 0)
                {
                    AduMessageBoxs.Show("添加失败");
                    return;
                }
                AduMessageBoxs.Show("添加成功！");
                WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新心跳数据"), "RefreshHeart");
                App.proxSocket = null;
                var control = this.Parent as ContentControl;
                Window win = Window.GetWindow(control);
                var title = win?.Title;
                if (title != null)
                {
                    if (title != "HsServerHa")
                    {
                        win.Close();
                    }

                }
            }

        }

        private void AdapterSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string content = AdapterSelector.SelectedValue.ToString();
            var adpaterName=  content.Replace("System.Windows.Controls.ComboBoxItem: ", "");
            var adapter = NetWorkHelper.GetAdapterByName(adpaterName);
            IPInterfaceProperties ip = adapter.GetIPProperties();
            UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
            var index = 0;
            foreach (UnicastIPAddressInformation item in ipCollection)
            {
                if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    HeartIP.Text = item.Address.ToString();
                    break;
                }
            }
        }
    }
}
